#include "cmd_basics.h"
#include "cmd_parser.h"
#include "io_console.h"
#include "cmd_bind.h"

#include <string.h>

static void bcmd_alias()
{
	if (cmd_getToken()<=0)
	{
		io_error("Error: expecting alias name\n");
	}
	else
	{
		char name[1024];
		if (cmd_token[0]=='"')
		{
			io_error("Error: expected alias name, found string\n");
			return;
		}
		strcpy(name, cmd_token);

		if (cmd_getToken()<=0)
		{
			//print the alias
			char *ptr = cmd_getCombo(name);
			if (ptr)
				io_msg("%s\n", ptr);
			else
				io_error("Error: alias not found\n");
		}
		else
		{
			//add the alias
			if (cmd_token[0]=='"')
				cmd_cleanTokenString();

			cmd_add(name, cmd_token);
		}
	}
}

static void bcmd_bind()
{
	int key;

	if (cmd_getToken()<=0)
	{
		io_error("Error: expected key\n");
		return;
	}

	key = cmd_getKeyCode(cmd_token);
	if (key<=0)
	{
		io_error("Error: unknown key \"%s\"\n",cmd_token);
		return;
	}

	if (cmd_getToken()<=0)
	{
		//show binding
		const char *bind = cmd_getBind(key);
		if (bind)
			io_msg("%s\n",bind);
		else
			io_error("Error: not bound\n");
	}
	else
	{
		//bind
		if (cmd_token[0]=='"')
			cmd_cleanTokenString();
		cmd_bind(key, cmd_token);
	}

}

static void bcmd_print()
{
	if (cmd_getToken()<=0)
	{
		io_error("Error: print expected param\n");
		return;
	}

	if (cmd_token[0]=='"')
		cmd_cleanTokenString();

	io_msg("%s\n",cmd_token);
}

static void bcmd_unalias()
{
	if (cmd_getToken()<=0)
	{
		io_error("Error: expecting alias\n");
		return;
	}

	cmd_delete(cmd_token);
}

static void bcmd_unbind()
{
	int key;

	if (cmd_getToken()<=0)
	{
		io_error("Error: expected key\n");
		return;
	}

	key = cmd_getKeyCode(cmd_token);
	if (key<=0)
	{
		io_error("Error: unknown key \"%s\"\n",cmd_token);
		return;
	}

	cmd_bind(key, NULL);
}

static void bcmd_unbindAll()
{
	for (int i=0;i<K_LAST_KEY;i++)
		cmd_bind(i,NULL);
}

void cmd_registerBasicCommands()
{
	cmd_add("alias",bcmd_alias);
	cmd_add("bind",bcmd_bind);
	cmd_add("print",bcmd_print);
	cmd_add("unalias",bcmd_unalias);
	cmd_add("unbind",bcmd_unbind);
	cmd_add("unbindall",bcmd_unbindAll);
}